package com.spic.system.controller;

import com.spic.common.core.constant.UserConstants;
import com.spic.common.core.domain.R;
import com.spic.common.core.utils.SecurityUtils;
import com.spic.common.core.utils.StringUtils;
import com.spic.common.core.utils.poi.ExcelUtil;
import com.spic.common.core.web.controller.BaseController;
import com.spic.common.core.web.domain.AjaxResult;
import com.spic.common.core.web.page.TableDataInfo;
import com.spic.common.log.annotation.Log;
import com.spic.common.log.enums.BusinessType;
import com.spic.common.security.annotation.InnerAuth;
import com.spic.common.security.annotation.PreAuthorize;
import com.spic.common.security.utils.cache.UserCacheUtils;
import com.spic.system.api.domain.SysRole;
import com.spic.system.api.domain.SysUser;
import com.spic.system.api.dto.UserDTO;
import com.spic.system.api.model.LoginUser;
import com.spic.system.domain.UserExport;
import com.spic.system.service.*;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 用户信息
 *
 * @author ruoyi
 */
@RestController
@RequestMapping("/user")
public class SysUserController extends BaseController
{
    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysRoleService roleService;

   @Autowired
   private ISysPostService postService;

    @Autowired
    private ISysPermissionService permissionService;

    @Autowired
    private ISysConfigService configService;

    @GetMapping("/cache")
    public Map<Long, String> cache()
    {
        List<UserDTO> list = UserCacheUtils.getCache();
        return list.stream().collect(Collectors.toMap(UserDTO::getUserId, UserDTO::getNickName));
    }

    @GetMapping("/getCacheByUserId")
    public AjaxResult getCacheByUserId()
    {
        List<UserDTO> list = UserCacheUtils.getCache();
        Map<Long, String> collect = list.stream().collect(Collectors.toMap(UserDTO::getUserId, UserDTO::getUserName));
        return AjaxResult.success(collect);
    }

    /**
     * 从缓存中获取用户基本信息
     * userId：若不指定则默认获取当前用户id
     * @return
     */
    @GetMapping("/basic")
    public AjaxResult getCurrentUser(@RequestParam(required = false) Optional<Long> userId){
        UserDTO dto = UserCacheUtils.getCache().stream()
                .filter(item->userId.orElse(SecurityUtils.getUserId()).equals(item.getUserId()))
                .findFirst().orElse(new UserDTO());
        return AjaxResult.success(dto);
    }

    /**
     * 获取用户列表
     */
//    @PreAuthorize(hasPermi = "system:user:list")
    @GetMapping("/list")
    public TableDataInfo list(SysUser user)
    {
        startPage();
        List<SysUser> list = userService.selectUserList(user);
        return getDataTable(list);
    }

    @GetMapping("/list2")
    public AjaxResult list2(SysUser user)
    {
        List<SysUser> list = userService.selectUserList(user);
        return AjaxResult.success(list);
    }

    @PostMapping("/userInfo")
    public AjaxResult userInfo(@RequestBody SysUser user)
    {
        SysUser sysUser = userService.selectUserInfoByUser(user);
        return AjaxResult.success(sysUser);
    }

    @Log(title = "用户管理", businessType = BusinessType.EXPORT)
    @PreAuthorize(hasPermi = "system:user:export")
    @PostMapping("/export")
    public void export(HttpServletResponse response, SysUser user) throws IOException
    {
        List<SysUser> list = userService.selectUserList(user);
        ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
        util.exportExcel(response, list, "用户数据");
    }

    @Log(title = "用户管理", businessType = BusinessType.IMPORT)
    @PreAuthorize(hasPermi = "system:user:import")
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception
    {
        ExcelUtil<UserExport> util = new ExcelUtil<UserExport>(UserExport.class);
        List<UserExport> userList = util.importExcel(file.getInputStream());
        String operName = SecurityUtils.getUsername();
        String message = userService.importUser(userList, updateSupport, operName);
        return AjaxResult.success(message);
    }

    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response) throws IOException
    {
        ExcelUtil<UserExport> util = new ExcelUtil<UserExport>(UserExport.class);
        util.importTemplateExcel(response, "用户数据");
    }

    /**
     * 获取当前用户信息
     */
    @InnerAuth
    @GetMapping("/info/{username}")
    public R<LoginUser> info(@PathVariable("username") String username)
    {
        SysUser sysUser = userService.selectUserByUserName(username);
        if (StringUtils.isNull(sysUser))
        {
            return R.fail("用户名或密码错误");
        }
        // 角色集合
        Set<String> roles = permissionService.getRolePermission(sysUser.getUserId());
        // 权限集合
        Set<String> permissions = permissionService.getMenuPermission(sysUser.getUserId());
        LoginUser sysUserVo = new LoginUser();
        sysUserVo.setSysUser(sysUser);
        sysUserVo.setRoles(roles);
        sysUserVo.setPermissions(permissions);
        return R.ok(sysUserVo);
    }

    @GetMapping("/getSysUserByUserIds/{userIds}")
    public AjaxResult getSysUserByUserIds(@PathVariable("userIds") String userIds){
        return AjaxResult.success(userService.selectSysUserByUserIds(userIds));
    }
    /**
     * 注册用户信息
     */
    @InnerAuth
    @PostMapping("/register")
    public R<Boolean> register(@RequestBody SysUser sysUser)
    {
        String username = sysUser.getUserName();
        if (!("true".equals(configService.selectConfigByKey("sys.account.registerUser"))))
        {
            return R.fail("当前系统没有开启注册功能！");
        }
        if (UserConstants.NOT_UNIQUE.equals(userService.checkUserNameUnique(username)))
        {
            return R.fail("保存用户'" + username + "'失败，注册账号已存在");
        }
        return R.ok(userService.registerUser(sysUser));
    }

    /**
     * 获取用户信息
     *
     * @return 用户信息
     */
    @GetMapping("getInfo")
    public AjaxResult getInfo()
    {
        Long userId = SecurityUtils.getUserId();
        // 角色集合
        Set<String> roles = permissionService.getRolePermission(userId);
        // 权限集合
        Set<String> permissions = permissionService.getMenuPermission(userId);
        AjaxResult ajax = AjaxResult.success();
        ajax.put("user", userService.selectUserById(userId));
        ajax.put("roles", roles);
        ajax.put("permissions", permissions);
        return ajax;
    }

    /**
     * 根据用户编号获取详细信息
     */
//    @PreAuthorize(hasPermi = "system:user:query")
    @GetMapping(value = { "/", "/{userId}" })
    public AjaxResult getInfo(@PathVariable(value = "userId", required = false) Long userId)
    {
        userService.checkUserDataScope(userId);
        AjaxResult ajax = AjaxResult.success();
        List<SysRole> roles = roleService.selectRoleAll();
        ajax.put("roles", SysUser.isAdmin(userId) ? roles : roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
        ajax.put("posts", postService.selectPostAll());
        if (StringUtils.isNotNull(userId))
        {
            ajax.put(AjaxResult.DATA_TAG, userService.selectUserById(userId));
            ajax.put("postIds", postService.selectPostListByUserId(userId));
            ajax.put("roleIds", roleService.selectRoleListByUserId(userId));
        }
        return ajax;
    }

    /**
     * 新增用户
     */
    @PreAuthorize(hasPermi = "system:user:add")
    @Log(title = "用户管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Validated @RequestBody SysUser user)
    {
        if (UserConstants.NOT_UNIQUE.equals(userService.checkUserNameUnique(user.getUserName())))
        {
            return AjaxResult.error("新增用户'" + user.getUserName() + "'失败，登录账号已存在");
        }
        else if (StringUtils.isNotEmpty(user.getPhonenumber())
                && UserConstants.NOT_UNIQUE.equals(userService.checkPhoneUnique(user)))
        {
            return AjaxResult.error("新增用户'" + user.getUserName() + "'失败，手机号码已存在");
        }
        else if (StringUtils.isNotEmpty(user.getEmail())
                && UserConstants.NOT_UNIQUE.equals(userService.checkEmailUnique(user)))
        {
            return AjaxResult.error("新增用户'" + user.getUserName() + "'失败，邮箱账号已存在");
        }
        user.setCreateBy(SecurityUtils.getUsername());
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        return toAjax(userService.insertUser(user));
    }

    /**
     * 新增用户
     */
    @PostMapping("/addNoAuth")
    public AjaxResult addNoAuth(@Validated @RequestBody SysUser user)
    {
        if (UserConstants.NOT_UNIQUE.equals(userService.checkUserNameUnique(user.getUserName())))
        {
            return AjaxResult.error("新增用户'" + user.getUserName() + "'失败，登录账号已存在");
        }
        user.setCreateBy("admin");
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        return toAjax(userService.insertUser(user));
    }

    /**
     * 修改用户
     */
    @PreAuthorize(hasPermi = "system:user:edit")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody SysUser user)
    {
        userService.checkUserAllowed(user);
        if (StringUtils.isNotEmpty(user.getPhonenumber())
                && UserConstants.NOT_UNIQUE.equals(userService.checkPhoneUnique(user)))
        {
            return AjaxResult.error("修改用户'" + user.getUserName() + "'失败，手机号码已存在");
        }
        else if (StringUtils.isNotEmpty(user.getEmail())
                && UserConstants.NOT_UNIQUE.equals(userService.checkEmailUnique(user)))
        {
            return AjaxResult.error("修改用户'" + user.getUserName() + "'失败，邮箱账号已存在");
        }
        user.setUpdateBy(SecurityUtils.getUsername());
        return toAjax(userService.updateUser(user));
    }

    @PutMapping("/updateCid")
    public AjaxResult updateCid( @RequestBody SysUser user)
    {
        return toAjax(userService.updateUserCid(user));
    }

    /**
     * 删除用户
     */
    @PreAuthorize(hasPermi = "system:user:remove")
    @Log(title = "用户管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{userIds}")
    public AjaxResult remove(@PathVariable Long[] userIds)
    {
        if (ArrayUtils.contains(userIds, SecurityUtils.getUserId()))
        {
            return AjaxResult.error("当前用户不能删除");
        }
        return toAjax(userService.deleteUserByIds(userIds));
    }

    /**
     * 重置密码
     */
    @PreAuthorize(hasPermi = "system:user:edit")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping("/resetPwd")
    public AjaxResult resetPwd(@RequestBody SysUser user)
    {
        userService.checkUserAllowed(user);
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        user.setUpdateBy(SecurityUtils.getUsername());
        return toAjax(userService.resetPwd(user));
    }

    /**
     * 状态修改
     */
    @PreAuthorize(hasPermi = "system:user:edit")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping("/changeStatus")
    public AjaxResult changeStatus(@RequestBody SysUser user)
    {
        userService.checkUserAllowed(user);
        user.setUpdateBy(SecurityUtils.getUsername());
        return toAjax(userService.updateUserStatus(user));
    }

    /**
     * 根据用户编号获取授权角色
     */
    @PreAuthorize(hasPermi = "system:user:query")
    @GetMapping("/authRole/{userId}")
    public AjaxResult authRole(@PathVariable("userId") Long userId)
    {
        AjaxResult ajax = AjaxResult.success();
        SysUser user = userService.selectUserById(userId);
        List<SysRole> roles = roleService.selectRolesByUserId(userId);
        ajax.put("user", user);
        ajax.put("roles", SysUser.isAdmin(userId) ? roles : roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
        return ajax;
    }

    /**
     * 用户授权角色
     */
    @PreAuthorize(hasPermi = "system:user:edit")
    @Log(title = "用户管理", businessType = BusinessType.GRANT)
    @PutMapping("/authRole")
    public AjaxResult insertAuthRole(Long userId, Long[] roleIds)
    {
        userService.insertUserAuth(userId, roleIds);
        return success();
    }
    @GetMapping("/treeuser")
    @ResponseBody
    public List<Map<String,Object>> treeuser() {

        List<Map<String, Object>> treeuser = userService.treeuser(0);
        return treeuser;
    }

    @GetMapping("/treeuser/app")
    @ResponseBody
    public List<Map<String,Object>> treeuserOfApp() {
        List<Map<String, Object>> treeuser = userService.treeuserOfApp(0);
        return treeuser;
    }

    @GetMapping("/treeuser/app2")
    @ResponseBody
    public List<Map<String,Object>> treeuserOfApp2() {
        List<Map<String, Object>> treeuser = userService.treeuserOfApp2(100);
        return treeuser;
    }

    @GetMapping("/treeuser/announceRoleTree")
    @ResponseBody
    public List<Map<String,Object>> announceRoleTree() {
        List<Map<String, Object>> treeuser = userService.announceRoleTree(100);
        return treeuser;
    }

    @GetMapping("/treeuser/announceDeptTreeAuth")
    @ResponseBody
    public List<Map<String,Object>> announceDeptTreeAuth() {
        List<Map<String, Object>> treeuser = userService.announceDeptTreeAuth(100);
        return treeuser;
    }

    /**
     * 操作票定制选人部门接口
     * @return
     */
    @GetMapping("/treeuser/getDdUserByDeptId")
    @ResponseBody
    public List<Map<String,Object>> getDdUserByDeptId() {
        List<Map<String, Object>> treeuser = userService.treeuserDdUserByDeptId(100);
        return treeuser;
    }

    @GetMapping("/cascaderuser/{planTeamLevel}")
    @ResponseBody
    public List<Map<String,Object>>cascaderuser(@PathVariable("planTeamLevel")String planTeamLevel) {
        List<Map<String, Object>> cascaderuser=new ArrayList<>();
        if("0".equals(planTeamLevel)){
            cascaderuser  = userService.cascaderuser(0);
        }else{
            cascaderuser =userService.findUserByOrgId1(Long.valueOf(SecurityUtils.getDeptId()));
        }
        return cascaderuser;
    }

    /**
     * 根据部门ID获取用户列表
     * @param deptId 部门Id
     * @return 用户列表
     */
    @GetMapping("/list/{deptId}")
    public AjaxResult getUsersByDept(@PathVariable("deptId")long deptId)
    {
        List<Map<String, Object>> users = userService.findUserByOrgId1(deptId);
        return AjaxResult.success(users);
    }

    @GetMapping("/listByIdStr/{deptId}")
    public AjaxResult listByIdStr(@PathVariable("deptId")long deptId)
    {
        List<Map<String, Object>> users = userService.findUserByOrgIdStr(deptId);
        return AjaxResult.success(users);
    }

    /**
     * 通过用户ID查找用户
     * @param userId
     * @return
     */
    @GetMapping(value = { "/lists/{userId}"})
    public AjaxResult  getUserById(@PathVariable("userId")Long userId){
        SysUser sysUsers = userService.selectUserById(userId);
        return AjaxResult.success(sysUsers);
    }

    /**
     * 通过用户姓名查找用户
     * @param userName
     * @return
     */
    @PostMapping("/listsByName")
    public AjaxResult  getUserByName(String userName){
        SysUser sysUser = userService.selectUserByUserName(userName);
        return AjaxResult.success(sysUser);
    }

    @GetMapping("/userPost")
    @ResponseBody
    public AjaxResult getPostUser() {
        List<Map<String, Object>> userPost = userService.getPostUser();
        return AjaxResult.success(userPost);
    }

    /**
     * 通过部门id获取部门违章管理员id
     * @param deptId 部门id
     * @return
     */
    @GetMapping(value = { "/getWzUserId/{deptId}"})
    public AjaxResult  getWzUserId(@PathVariable("deptId")String deptId){
        SysUser user = userService.selectWzUserIdByDeptId(deptId);
        return AjaxResult.success(user);
    }

    /**
     * 根据部门ids查询 部门主任
     * @param deptIds
     * @return 用户
     */
    @GetMapping("/getSysUserByDeptIds/{deptIds}")
    public AjaxResult getSysUserByDeptIds (@PathVariable Long[] deptIds){
        List<SysUser> sysUsers = userService.selectUserByZhuRenDeptId(deptIds);
        return AjaxResult.success(sysUsers);
    }

    @GetMapping("/getSysUserByRoleAndDeptId")
    public AjaxResult getSysUserByRoleAndDeptId (@RequestParam Map<String,Object> map){
        List<Map<String,Object>> sysUsers = userService.getSysUserListByRoleAndDept(map);
        return AjaxResult.success(sysUsers);
    }

    @GetMapping("/selectAdminByRoleAndDept")
    public AjaxResult selectAdminByRoleAndDept (@RequestParam Map<String,Object> map){
        List<Map<String,Object>> sysUsers = userService.selectAdminByRoleAndDept(map);
        return AjaxResult.success(sysUsers);
    }

    @GetMapping("/getUserListByParentId/{parentDeptId}")
    public AjaxResult  getUserListByParentId(@PathVariable("parentDeptId")Long parentDeptId){
        Long [] sysUsers = userService.getUserListByParentId(parentDeptId);
        return AjaxResult.success(sysUsers);
    }

    /**
     * 按部门列表查询用户
     * @param deptSep  部门数组
     * @return 用户列表
     */
    @GetMapping("/users/{depts}")
    public AjaxResult listUserByDepts(@PathVariable("depts") Long[]  deptSep)
    {
        List<SysUser> sysUsers = userService.listUserByDepts(deptSep);
        return AjaxResult.success(sysUsers);
    }


}
